import 'package:flutter_axrjc/datasource/network/api/LightApi.dart';
import 'package:flutter_axrjc/datasource/network/bean/AssetBean.dart';
import 'package:flutter_axrjc/datasource/network/request/exp.dart';
import 'package:flutter_axrjc/widget/image_picker_dialog.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:image_cropper/image_cropper.dart';

import 'state.dart';

class AddLightLogic extends GetxController {
  final AddLightState state = AddLightState();
  @override
  void onInit() {
    super.onInit();
    refreshImg();
    getAllType();
    getAllBrandType();
  }

  Future<void> addLight() async {
    if (state.fixtureType.value.isEmpty) {
      EasyLoading.showToast("请选择灯具类型");
      return;
    }
    try {
      await LightApi.add(
          // brightnessAdjustment: state.lux.value,
          imgFile: state.originImgList,
          // colorTemperatureAdjustment: state.colorTemperatureAdjustment.value,
          fixtureBrand: state.fixtureBrandCode.value,
          fixtureModel: state.fixtureModelId.value,
          fixtureName: state.fixtureName.value,
          fixtureType: state.fixtureType.value,
          installationDate: state.installDate.value,
          remark: state.remark.value);
    } on ApiException catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast("$e");
    }
  }

  Future<void> addImg() async {
    AssetBean? a = await showSingleMedia();
    if (a == null) {
      return;
    }

    CroppedFile? file = await ImageCropper().cropImage(sourcePath: a.path);
    if (file == null) {
      return;
    }
    state.originImgList.add(file.path);
    refreshImg();
  }

  void refreshImg() {
    state.imgList.clear();
    state.imgList.add("add");
    state.imgList.addAll(state.originImgList);
  }

  Future<void> getAllType() async {
    state.types.clear();
    state.types.addAll(await LightApi.getAllType());

    if (state.types.isNotEmpty) {
      state.fixtureType.value = state.types.first.codeCode ?? '';
      state.fixtureTypeName.value = state.types.first.codeName ?? '';
    }
  }

  Future<void> getAllBrandType() async {
    state.brandType.clear();
    state.brandType.addAll(await LightApi.getBrandType());
    if (state.brandType.isNotEmpty) {
      state.fixtureBrand.value = state.brandType.first.lampBrandName ?? '';
      state.fixtureBrandCode.value = state.brandType.first.lampBrandCode ?? '';

      state.currentBrandTypes.clear();
      state.currentBrandTypes.addAll(state.brandType
              .firstWhere((element) =>
                  element.lampBrandCode == state.fixtureBrandCode.value)
              .baseLampTypes ??
          []);

      if (state.currentBrandTypes.isNotEmpty) {
        state.fixtureModelId.value =
            state.currentBrandTypes.first.lampTypeId ?? '';
        state.fixtureModelName.value =
            state.currentBrandTypes.first.lampTypeName ?? '';
      }
    }
  }
}
